package com.newway.common.context;

import com.newway.common.exception.UserInfoException;
import com.newway.common.login.LoginUser;
import com.newway.common.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    @Autowired
    JwtTokenUtil jwtTokenUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("当前请求地址：================"+requestURI);
        LoginUser loginUser = jwtTokenUtil.getLoginUser(request);
        if(loginUser == null|| loginUser.getUserInfo()==null){
            throw new UserInfoException(10001,"用户登录状态失效");
        }
        jwtTokenUtil.verifyToken(loginUser);
        UserInfo userInfo = loginUser.getUserInfo();
        UserInfoContext.putUserInfo(userInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoContext.removeUserInfo();
    }
}
